﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.IO;

namespace Core.Shop.Tool
{
    public class RedisHelper
    {
        private static ConnectionMultiplexer RedisMultiplexer;

        IDatabase db = null;

        public RedisHelper()
        {
            var _configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
            var redisStr = _configuration.GetConnectionString("RedisConnection");
            RedisMultiplexer = ConnectionMultiplexer.Connect(redisStr);
            db = RedisMultiplexer.GetDatabase(0);
        }

        #region String 
        /// <summary>
        /// 保存单个key value
        /// </summary>
        /// <param name="value">保存的值</param>
        /// <param name="expiry">过期时间</param>
        public bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
        {
            return db.StringSet(key, value, expiry);
        }

        /// <summary>
        /// 获取单个key的值
        /// </summary>
        public RedisValue GetStringKey(string key)
        {
            return db.StringGet(key);
        }


        /// <summary>
        /// 获取一个key的对象
        /// </summary>
        public T GetStringKey<T>(string key)
        {
            if (db == null)
            {
                return default;
            }
            var value = db.StringGet(key);
            if (value.IsNullOrEmpty)
            {
                return default;
            }
            return JsonConvert.DeserializeObject<T>(value);
        }

        /// <summary>
        /// 保存一个对象
        /// </summary>
        /// <param name="obj"></param>
        public bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
        {
            if (db == null)
            {
                return false;
            }
            string json = JsonConvert.SerializeObject(obj);
            return db.StringSet(key, json, expiry);
        }


        /// <summary>
        /// 保存Hach key value
        /// </summary>
        /// <param name="value">保存的值</param>
        /// <param name="expiry">过期时间</param>
        public bool SetHash(string key, RedisValue hashFiled, RedisValue hachValue)
        {
            return db.HashSet(key, hashFiled, hachValue);
        }


        public RedisValue GetHashFiled(string key, RedisValue hashFiled)
        {
            return db.HashGet(key, hashFiled);
        }

        public HashEntry[] GetHashList(string key)
        {
            return db.HashGetAll(key);
        }

        public void Delete(string key)
        {
            db.KeyDelete(key);
        }

        public bool HashFieldExsits(string key, RedisValue hashFiled)
        {
            return db.HashExists(key, hashFiled);

        }

        #endregion
    }
}
